package com.baselibrary.libs.Utils.netUtils.NoHttp.queueList;


import android.content.Context;
import android.os.SystemClock;
import android.util.Log;
import android.webkit.URLUtil;

import com.alibaba.fastjson.JSONObject;
import com.baselibrary.libs.Utils.db.DAO.CacheManage;
import com.baselibrary.libs.Utils.log.LogUtils;
import com.baselibrary.libs.Utils.netUtils.NoHttp.queue.Request_netWork;
import com.baselibrary.libs.Utils.netUtils.NoHttp.queue.Request_netWork_error;
import com.baselibrary.libs.Utils.netUtils.NoHttp.queue.TaskExecutor;
import com.baselibrary.libs.Utils.netUtils.NoHttp.queue.YolandaLinkedQueue;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Hashtable;

/**
 * Created by Administrator 于萌萌
 * 创建日期: 17:36 . 2017年02月23日
 * 描述:
 * <p>
 * <p>
 * 备注:
 */

public class QueueNetWork extends YolandaLinkedQueue<Request_netWork,Request_netWork_error, Integer, JSONObject> {
    static QueueNetWork mQueueNetWork;
    static CacheManage sCacheManage;
    public QueueNetWork(int poolSize) {
        super(poolSize);
    }
    static  Context mContext;

    public static QueueNetWork getControlQueue(Context context, int poolSize,int chechSize){
        mContext =context;
        if (mQueueNetWork==null){
            mQueueNetWork = new QueueNetWork(poolSize);
            sCacheManage = new CacheManage(chechSize);
            mQueueNetWork.start();
            return mQueueNetWork;
        }
        return mQueueNetWork;
    }

    @Override
    public void getData(Request_netWork request, TaskExecutor<Request_netWork, Request_netWork_error, Integer, JSONObject> taskExecutor, YolandaLinkedQueue<Request_netWork, Request_netWork_error, Integer, JSONObject> queue) {
        sCacheManage.find(mContext,queue,request);


        SystemClock.sleep(2*1000);

        //参数
        Hashtable<String, String> hashtable = request.getHashtable();
        //地址
        String netUrl = request.getUrl();
        Request_netWork_error error = new Request_netWork_error();
        JSONObject msgObject = new JSONObject();
        HttpURLConnection connection = null;
        try {
            if (!URLUtil.isNetworkUrl(netUrl)) {
                return;
            }
            URL url = new URL(netUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(false);
            connection.setConnectTimeout(10 * 1000);
            connection.setReadTimeout(10 * 1000);
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Charset", "UTF-8");
            //	connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
            connection.setRequestProperty("Accept-Encoding", "identity");
            connection.connect();
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.writeBytes(hashtable.toString());
            out.flush();
            out.close();



            int responseCode = connection.getResponseCode();
            LogUtils.i("请求码是"+responseCode);
            if (responseCode == 200) {
                ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
                InputStream inputStream = new BufferedInputStream(connection.getInputStream());
                //获取网络文件的大小   .setRequestProperty("Accept-Encoding", "identity");
                //这样设置获取到了正常的 网络文件大小  不能要压缩的
                int total = connection.getContentLength();
                //获取本地文件的大小
                //long total = inputStream.available();
                String totalstr = String.valueOf(total);
                Log.d("文件大小", totalstr);
                int len = 0;
                int length = 0;
                byte[] buffer = new byte[512];
                while ((len = inputStream.read(buffer)) != -1) {
                    arrayOutputStream.write(buffer, 0, len);
                    length += len;
                    //演示进度
                    //SystemClock.sleep(1*200);
                    //算出来的值
                    int progress = (int) (length * 100L / total);
                    // onPostUpdate(progress);
                    queue.onUpData(request,progress);
                }
                inputStream.close();
                arrayOutputStream.flush();
                inputStream.close();


                JSONObject jsonObject =
                        JSONObject.parseObject(new String(arrayOutputStream.toByteArray()));


                LogUtils.i("json 内容是"+request);
                // queue.getResult(request);

                queue.onResult(request,jsonObject);

            }

        } catch (ProtocolException e) {
            e.printStackTrace();
            error.setTag(request.getTag());
            error.setMsg("网络协议异常");
            queue.onParam(request,error);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            error.setTag(request.getTag());
            error.setMsg("访问路径出错");
            queue.onParam(request,error);
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
            error.setTag(request.getTag());
            error.setMsg("连接超时");
            queue.onParam(request, error);
        } catch (UnknownHostException e) {
            e.printStackTrace();
            error.setTag(request.getTag());
            error.setMsg("未知得主机错误");
            queue.onParam(request, error);
        } catch (ConnectException e) {
            e.printStackTrace();
            error.setTag(request.getTag());
            error.setMsg("获取网络数据失败");
            queue.onParam(request, error);
        } catch (IOException e) {
            e.printStackTrace();
            error.setTag(request.getTag());
            error.setMsg("获取网络数据失败");
            queue.onParam(request,error);
        }
    }

//    private void findMemory(YolandaLinkedQueue<Request_netWork, Request_netWork_error, Integer, JSONObject> queue, final Request_netWork request) {
//
//
//        findDB(mContext,queue,request);
//    }

//    private void findDB(Context context,final YolandaLinkedQueue<Request_netWork, Request_netWork_error, Integer, JSONObject> queue, final Request_netWork request) {
//        LogUtils.i("缓存 步骤"+"查找回显"+request);
//        //获取缓存
//
//
//       new CacheDb(context)
//               .getDbCache(request,queue);
//
//        //
//    }
//    private void addDB(Context context,Request_netWork request, JSONObject jsonObject) {
//        //获取缓存
//
//        new CacheDb(mContext)
//                .addDbCache(request,jsonObject);
//
//    }
    @Override
    public void getResult(Request_netWork request, JSONObject jsonObject) {
        LogUtils.i("访问网络 结果是什么"+request);
        sCacheManage.add(mContext,request,jsonObject);
        //添加缓存


        LogUtils.i("缓存步骤"+"获取成功添加");
        request.setResult(jsonObject);
    }


    @Override
    public void getUpData(Request_netWork request, Integer integer) {
        LogUtils.i("访问网络 过程是什么"+integer);
        request.setUpData(integer);
    }

    @Override
    public void getParam(Request_netWork request, Request_netWork_error request_netWork_error) {
        LogUtils.i("访问网络 失败是什么"+request_netWork_error);
        request.setParam_error(request_netWork_error);
    }

    @Override
    public void getStart(Request_netWork request,JSONObject jsonObject) {

        request.setStart(jsonObject);
    }



}
